package com.fusion.lottery.mapper.auth;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.fusion.lottery.entity.auth.Role;
import com.fusion.lottery.entity.auth.Source;
import com.fusion.lottery.entity.auth.User;

public interface UserMapper {
	
	/**
	 * 查询用户
	 * @param user
	 * @param start
	 * @param pageSize
	 * @return
	 */
	@Select({
		"<script>",
		"SELECT * FROM t_auth_user ",
		" <when test='pageSize > 0'> limit #{start},#{pageSize}</when> ",
		"</script>"
		})
	List<User> list(User user,@Param("start")long start,@Param("pageSize")long pageSize);
	
	/**
	 * 统计用户数量
	 * @param user
	 * @return
	 */
	@Select("SELECT count(1) FROM t_auth_user")
	long count(User user);
	
	/**
	 * 查询用户详情
	 * @param userId
	 * @return
	 */
	@Select("SELECT * FROM t_auth_user WHERE id = #{userId}")
	User get(String userId);
	
	/**
	 * 添加用户
	 * @param user
	 */
	@Insert("INSERT INTO t_auth_user(id,phone,password,salt,createTime,status,type,name,photo,openId) "
			+ "VALUES(#{id}, #{phone}, #{password}, #{salt}, #{createTime}, #{status}, #{type}, #{name}, #{photo}, #{openId})")
	@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")
	void insert(User user);
	
	/**
	 * 删除用户
	 * @param userId
	 */
	@Delete("DELETE FROM t_auth_user WHERE id =#{userId}")
	void delete(String userId);
	
	/**
	 * 修改用户信息
	 * @param user
	 */
	@Update({"<script>",
		"update t_auth_user set id=id ",
		" <when test='phone != null '> ,phone=#{phone}</when> ",
		" <when test='name != null '> ,name=#{name}</when> ",
		" <when test='photo != null '> ,photo=#{photo}</when> ",
		" <when test='password != null '> ,password=#{password}</when> ",
		" <when test='status != null '> ,status=#{status}</when> ",
		" <when test='type != null '> ,type=#{type}</when> ",
		" where id= #{id}",
		"</script>"})
	void update(User user);
	
	/**
	 * 获取用户拥有的角色
	 * @param userId
	 * @return
	 */
	@Select("SELECT r.id,r.`name`,r.code FROM t_auth_authorization a,t_auth_role r "
			+ "WHERE a.roleId = r.id AND r.`status` = 0 AND a.userId= #{userId}")
	List<Role> getRole(String userId);
	
	/**
	 * 获取用户权限
	 * @param userId
	 * @return
	 */
	@Select("SELECT t.id,t.`name`,t.code FROM t_auth_authorization a,t_auth_role r,t_auth_resource_assignments s,t_auth_security_resources t "
			+ "WHERE a.roleId = r.id AND r.`status` = 0 AND r.id = s.roleId AND s.sourceId = t.id AND r.`status` = 0 AND t.`status` =0 AND a.userId= #{userId}")
	List<Source> getPermission(String userId);
}
